/**
 * 全局字段映射配置
 * 统一管理所有业务模块的字段映射关系
 */

import { FieldMapping, FieldTransformer } from '../utils/fieldTransform';

// ===== 证券投资计划字段映射 =====
export const STOCK_PLAN_FIELD_MAPPING: FieldMapping = {
  id: 'id',
  userId: 'user_id',
  stockCode: 'stock_code',
  stockName: 'stock_name',
  currentPrice: 'current_price',
  maxDrawdown: 'max_drawdown',
  totalShares: 'total_shares',
  buyTimes: 'buy_times',
  strategy: 'strategy',
  averagePrice: 'average_price',
  totalAmount: 'total_amount',
  minLots: 'min_lots',
  lotSize: 'lot_size',
  stockType: 'stock_type',
  trackingIndex: 'tracking_index',
  managementFee: 'management_fee',
  riskLevel: 'risk_level',
  maxLoss: 'max_loss',
  createdAt: 'created_at',
  updatedAt: 'updated_at'
};

// ===== 基金投资计划字段映射 =====
export const FUND_PLAN_FIELD_MAPPING: FieldMapping = {
  id: 'id',
  userId: 'user_id',
  fundCode: 'fund_code',
  fundName: 'fund_name',
  fundType: 'fund_type',
  currentNav: 'current_nav',
  investmentAmount: 'investment_amount',
  purchaseDate: 'purchase_date',
  expectedReturn: 'expected_return',
  riskRating: 'risk_rating',
  managementFee: 'management_fee',
  custodianFee: 'custodian_fee',
  salesFee: 'sales_fee',
  redemptionFee: 'redemption_fee',
  minInvestment: 'min_investment',
  fundManager: 'fund_manager',
  fundCompany: 'fund_company',
  establishDate: 'establish_date',
  fundScale: 'fund_scale',
  createdAt: 'created_at',
  updatedAt: 'updated_at'
};

// ===== 收益计算字段映射 =====
export const PROFIT_CALCULATION_FIELD_MAPPING: FieldMapping = {
  id: 'id',
  userId: 'user_id',
  calculationType: 'calculation_type',
  assetType: 'asset_type',
  assetCode: 'asset_code',
  assetName: 'asset_name',
  initialInvestment: 'initial_investment',
  currentValue: 'current_value',
  totalProfit: 'total_profit',
  profitRate: 'profit_rate',
  holdingPeriod: 'holding_period',
  annualizedReturn: 'annualized_return',
  dividendIncome: 'dividend_income',
  capitalGain: 'capital_gain',
  totalCost: 'total_cost',
  netProfit: 'net_profit',
  calculationDate: 'calculation_date',
  createdAt: 'created_at',
  updatedAt: 'updated_at'
};

// ===== 用户设置字段映射 =====
export const USER_SETTINGS_FIELD_MAPPING: FieldMapping = {
  id: 'id',
  userId: 'user_id',
  settingKey: 'setting_key',
  settingValue: 'setting_value',
  settingType: 'setting_type',
  settingCategory: 'setting_category',
  settingDescription: 'setting_description',
  isDefault: 'is_default',
  isActive: 'is_active',
  sortOrder: 'sort_order',
  createdAt: 'created_at',
  updatedAt: 'updated_at'
};

// ===== 用户配置文件字段映射 =====
export const USER_PROFILE_FIELD_MAPPING: FieldMapping = {
  id: 'id',
  email: 'email',
  name: 'name',
  username: 'username',
  role: 'role',
  avatarUrl: 'avatar_url',
  phone: 'phone',
  bio: 'bio',
  isActive: 'is_active',
  createdAt: 'created_at',
  updatedAt: 'updated_at'
};

// ===== 创建转换器实例 =====
export const stockPlanTransformer = new FieldTransformer(STOCK_PLAN_FIELD_MAPPING);
export const fundPlanTransformer = new FieldTransformer(FUND_PLAN_FIELD_MAPPING);
export const profitCalculationTransformer = new FieldTransformer(PROFIT_CALCULATION_FIELD_MAPPING);
export const userSettingsTransformer = new FieldTransformer(USER_SETTINGS_FIELD_MAPPING);
export const userProfileTransformer = new FieldTransformer(USER_PROFILE_FIELD_MAPPING);

// ===== 转换器映射表 =====
export const TRANSFORMERS = {
  stock_investment_plans: stockPlanTransformer,
  fund_investment_plans: fundPlanTransformer,
  profit_calculations: profitCalculationTransformer,
  user_settings: userSettingsTransformer,
  user_profiles: userProfileTransformer
} as const;

// ===== 根据表名获取转换器 =====
export function getTransformerByTableName(tableName: string): FieldTransformer | null {
  return TRANSFORMERS[tableName as keyof typeof TRANSFORMERS] || null;
}

// ===== 字段映射验证 =====
export function validateFieldMapping(mapping: FieldMapping): boolean {
  try {
    // 检查映射是否为空
    if (!mapping || Object.keys(mapping).length === 0) {
      console.warn('字段映射为空');
      return false;
    }
    
    // 检查是否有重复的数据库字段名
    const dbFields = Object.values(mapping);
    const uniqueDbFields = new Set(dbFields);
    if (dbFields.length !== uniqueDbFields.size) {
      console.warn('字段映射中存在重复的数据库字段名');
      return false;
    }
    
    // 检查字段名格式
    const camelCaseRegex = /^[a-z][a-zA-Z0-9]*$/;
    const snakeCaseRegex = /^[a-z][a-z0-9_]*$/;
    
    for (const [camelKey, snakeKey] of Object.entries(mapping)) {
      if (!camelCaseRegex.test(camelKey)) {
        console.warn(`前端字段名格式不正确: ${camelKey}`);
        return false;
      }
      
      if (!snakeCaseRegex.test(snakeKey)) {
        console.warn(`数据库字段名格式不正确: ${snakeKey}`);
        return false;
      }
    }
    
    return true;
  } catch (error) {
    console.error('字段映射验证失败:', error);
    return false;
  }
}

// ===== 导出所有字段映射配置 =====
export const ALL_FIELD_MAPPINGS = {
  STOCK_PLAN_FIELD_MAPPING,
  FUND_PLAN_FIELD_MAPPING,
  PROFIT_CALCULATION_FIELD_MAPPING,
  USER_SETTINGS_FIELD_MAPPING,
  USER_PROFILE_FIELD_MAPPING
};

// ===== 初始化验证 =====
export function initializeFieldMappings(): boolean {
  console.log('开始验证字段映射配置...');
  
  let allValid = true;
  
  for (const [name, mapping] of Object.entries(ALL_FIELD_MAPPINGS)) {
    const isValid = validateFieldMapping(mapping);
    if (!isValid) {
      console.error(`字段映射验证失败: ${name}`);
      allValid = false;
    } else {
      console.log(`字段映射验证通过: ${name}`);
    }
  }
  
  if (allValid) {
    console.log('所有字段映射配置验证通过');
  } else {
    console.error('部分字段映射配置验证失败');
  }
  
  return allValid;
}

// 在模块加载时自动验证
if (process.env.NODE_ENV === 'development') {
  initializeFieldMappings();
}